package com.bw.z.mvp.view.user.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bw.z.R;
import com.bw.z.db.DBManager;
import com.bw.z.db.UserTable;
import com.bw.z.db.UserTableDao;
import com.bw.z.mvp.base.view.BaseActivity;
import com.bw.z.mvp.contract.InformationContract;
import com.bw.z.mvp.di.DaggerInformationComponent;
import com.bw.z.mvp.di.InformationModules;
import com.bw.z.mvp.model.entity.FileEntity;
import com.bw.z.mvp.presenter.InformationPresenter;
import com.bw.z.utils.GlideUtils;
import com.bw.z.utils.SpUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class InformationActivity extends BaseActivity<InformationPresenter> implements InformationContract.informationView, View.OnClickListener {

    private ImageView informationBack;
    private RelativeLayout rlImg;
    private RelativeLayout rlName;
    private TextView informationName;
    private RelativeLayout rlSex;
    private InformationBroadcast broadcast;
    private DBManager dbManager;
    private UserTableDao userTableDao;
    private TextView sexCancel;
    private TextView sexWoman;
    private TextView sexMan;
    private TextView sexSecret;
    private TextView avatarCancel;
    private TextView avatarLocal;
    private TextView avatarShoot;
    private TextView informationSex;
    private ImageView informationAvatar;
    private String path = "";
    private String uri = "";
    private PopupWindow popupWindowAvatar, popupWindowSex;
    private UserTable load;


    @Override
    public int bindLayout() {
        return R.layout.activity_information;
    }


    @Override
    public void initView() {
        getColors(Color.WHITE);
        // 注册广播
        broadcast = new InformationBroadcast();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("nickname");
        registerReceiver(broadcast, intentFilter);

        informationBack = findViewById(R.id.information_back);
        rlImg = findViewById(R.id.rl_img);
        rlName = findViewById(R.id.rl_name);
        informationName = findViewById(R.id.information_name);
        rlSex = findViewById(R.id.rl_sex);
        informationSex = findViewById(R.id.information_sex);
        informationAvatar = findViewById(R.id.information_avatar);

        dbManager = new DBManager(this);
        userTableDao = dbManager.getDaoSession().getUserTableDao();
        Long user_id = SpUtils.readDataLong("user_id");
        com.bw.z.utils.LogUtils.show("user_id:" + user_id);
        if (user_id != 0l) {
            load = userTableDao.load(user_id);
        }
        if (load != null) {
            if (load.getUser_name() != null)
                informationName.setText(load.getUser_name() + "");
            if (load.getUser_sex() != null) {
                if (load.getUser_sex().equals("0"))
                    informationSex.setText("男");
                else
                    informationSex.setText("女");
            }
            if (load.getUser_img() != null)
                GlideUtils.getInstance().GlideCircleCropImage(load.getUser_img(), informationAvatar);
        }


        View view = LayoutInflater.from(this).inflate(R.layout.pop_avatar, null);
        avatarShoot = view.findViewById(R.id.avatar_shoot);
        avatarLocal = view.findViewById(R.id.avatar_local);
        avatarCancel = view.findViewById(R.id.avatar_cancel);
        popupWindowAvatar = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, false);
        popupWindowAvatar.setContentView(view);

        View inflate = LayoutInflater.from(this).inflate(R.layout.pop_sex, null);
        sexSecret = inflate.findViewById(R.id.sex_secret);
        sexMan = inflate.findViewById(R.id.sex_man);
        sexWoman = inflate.findViewById(R.id.sex_woman);
        sexCancel = inflate.findViewById(R.id.sex_cancel);
        popupWindowSex = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, false);
        popupWindowSex.setContentView(inflate);

        rlImg.setOnClickListener(this::onClick);
        avatarShoot.setOnClickListener(this::onClick);
        avatarLocal.setOnClickListener(this::onClick);
        avatarCancel.setOnClickListener(this::onClick);
        rlSex.setOnClickListener(this::onClick);
        sexSecret.setOnClickListener(this::onClick);
        sexMan.setOnClickListener(this::onClick);
        sexWoman.setOnClickListener(this::onClick);
        sexCancel.setOnClickListener(this::onClick);
        rlName.setOnClickListener(this::onClick);
        informationBack.setOnClickListener(this::onClick);
    }


    @Override
    public View addStatusView() {
        return f(R.id.information_linear);
    }

    public void setWindow() {
        WindowManager.LayoutParams attributes = getWindow().getAttributes();
        attributes.alpha = 1f;
        getWindow().setAttributes(attributes);
//        popupWindow.dismiss();
    }

    public String time() {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMMdd_HHmmss");
        String format = simpleDateFormat.format(date);
        return "IMG" + format + ".jpg";
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Long user_id = SpUtils.readDataLong("user_id");
        UserTable load = userTableDao.load(user_id);
        if (requestCode == 102 && resultCode == Activity.RESULT_OK) {

            GlideUtils.getInstance().GlideCircleCropImage(path, informationAvatar);

            load.setUser_img(path);
            userTableDao.update(load);

            p.requestFile(path);
            p.getUserUpload(load.getUser_id(), load.getUser_img(), load.getUser_integral(), load.getUser_name(), load.getUser_phone(), load.getUser_pwd(), load.getUser_sex());
            //发送广播并传值
            Intent intent = new Intent();
            intent.setAction("path");
            intent.putExtra("path", path);
            sendBroadcast(intent);
        } else if (requestCode == 103 && resultCode == Activity.RESULT_OK) {
            //上传头像路径获取  修改
            Uri data1 = data.getData();
            Cursor cursor = getContentResolver().query(data1, null, null, null, null);
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    uri = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                }
            }
            load.setUser_img(uri);
            userTableDao.update(load);
            LogUtils.e("uri:" + uri);
            //发送广播并传值
            Intent intent = new Intent();
            intent.setAction("path");
            intent.putExtra("path", uri);
            sendBroadcast(intent);
            p.requestFile(uri);
            p.getUserUpload(load.getUser_id(), load.getUser_img(), load.getUser_integral(), load.getUser_name(), load.getUser_phone(), load.getUser_pwd(), load.getUser_sex());
            Glide.with(this).load(uri).transform(new CenterCrop(), new CircleCrop()).into(informationAvatar);
        }
    }

    @Override
    public void requestFile(FileEntity fileEntity) {
        LogUtils.json(fileEntity.getMsg());
        if (fileEntity.getStatuesCode().equals("200")) {
            Long user_id = SpUtils.readDataLong("user_id");
            UserTable load = userTableDao.load(user_id);
            p.getUserUpload(load.getUser_id(), load.getUser_img(), load.getUser_integral(), load.getUser_name(), load.getUser_phone(), load.getUser_pwd(), load.getUser_sex());
        }
    }

    @Override
    public void requestUpdateUser(UserTable userTable) {
        LogUtils.json(userTable.message);
    }

    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.rl_img:
                //更改头像
                popupWindowAvatar.showAtLocation(view, Gravity.BOTTOM, 0, 0);
                WindowManager.LayoutParams attributesImg = getWindow().getAttributes();
                attributesImg.alpha = 0.3f;
                getWindow().setAttributes(attributesImg);
                break;
            case R.id.avatar_shoot:
                //相机
                Intent intent_shoot = new Intent();
                intent_shoot.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                String str = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString();
                path = str + "/" + time();
                LogUtils.e("path:" + path);
                //使用fileprovider保存照片
                Uri uri = FileProvider.getUriForFile(this, "com.example.z", new File(path));
                LogUtils.e("uri:" + uri);
                intent_shoot.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(intent_shoot, 102);
                setWindow();
                popupWindowAvatar.dismiss();
                break;
            case R.id.avatar_local:
                //相册
                Intent intent_local = new Intent();
                intent_local.setAction(Intent.ACTION_PICK);
                intent_local.setType("image/*");
                startActivityForResult(intent_local, 103);
                setWindow();
                popupWindowAvatar.dismiss();
                break;
            case R.id.avatar_cancel:
                //取消拍照
                setWindow();
                popupWindowAvatar.dismiss();
                break;
            case R.id.information_back:
                //返回
                Intent intent = new Intent();
                intent.setAction("nickname");
                intent.putExtra("name", informationName.getText());
                sendBroadcast(intent);
                finish();
                break;
            case R.id.rl_name:
                //跳转页面更改昵称
                startActivity(new Intent(InformationActivity.this, NicknameActivity.class));
                break;
            case R.id.rl_sex:
                //更改性别
                popupWindowSex.showAtLocation(view, Gravity.BOTTOM, 0, 0);
                WindowManager.LayoutParams attributesSex = getWindow().getAttributes();
                getWindow().getAttributes();
                attributesSex.alpha = 0.3f;
                getWindow().setAttributes(attributesSex);
                //修改性别
                Long user_id = SpUtils.readDataLong("user_id");
                load = userTableDao.load(user_id);
                break;
            case R.id.sex_secret:
                //保密
                load.setUser_sex("0");
                userTableDao.update(load);
                p.getUserUpload(load.getUser_id(), load.getUser_img(), load.getUser_integral(), load.getUser_name(), load.getUser_phone(), load.getUser_pwd(), load.getUser_sex());
                informationSex.setText(sexSecret.getText().toString());
                setWindow();
                popupWindowSex.dismiss();
                break;
            case R.id.sex_man:
                //男
                load.setUser_sex("0");
                userTableDao.update(load);
                p.getUserUpload(load.getUser_id(), load.getUser_img(), load.getUser_integral(), load.getUser_name(), load.getUser_phone(), load.getUser_pwd(), load.getUser_sex());
                informationSex.setText(sexMan.getText().toString());
                setWindow();
                popupWindowSex.dismiss();
                break;
            case R.id.sex_woman:
                //女
                load.setUser_sex("1");
                userTableDao.update(load);
                p.getUserUpload(load.getUser_id(), load.getUser_img(), load.getUser_integral(), load.getUser_name(), load.getUser_phone(), load.getUser_pwd(), load.getUser_sex());
                informationSex.setText(sexWoman.getText().toString());
                setWindow();
                popupWindowSex.dismiss();
                break;
            case R.id.sex_cancel:
                //取消选择性别
                setWindow();
                popupWindowSex.dismiss();
                break;

        }
    }

    //广播接收者
    class InformationBroadcast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("nickname")) {
                UserTable load = userTableDao.load(SpUtils.readDataLong("user_id"));
                load.setUser_name("" + intent.getStringExtra("name"));
                userTableDao.update(load);
                p.getUserUpload(load.getUser_id(), load.getUser_img(), load.getUser_integral(), load.getUser_name(), load.getUser_phone(), load.getUser_pwd(), load.getUser_sex());
                informationName.setText("" + intent.getStringExtra("name"));
            }
        }
    }

    @Override
    public void inject() {
        DaggerInformationComponent.builder().informationModules(new InformationModules(this)).build().injectInformation(this);
    }

    @Override
    public void initData() {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcast);
    }
}